#!/usr/bin/perl
use lib "$ENV{MYSQL_DRAW}/lib";
use MyTools;
use strict;
use Data::Dumper;
use Getopt::Long;
use DBI;

my ($project_name, $flowcell_name, $flowcell_path, $seq_center, $read_length, $date, $submitter, $debug);
my @argv = @ARGV;
&GetOptions("debug!"=> \$debug,
            "project_name=s" => \$project_name,
            "flowcell_name=s" => \$flowcell_name,
            "flowcell_path=s" => \$flowcell_path,
            "seq_center=s" => \$seq_center,
            "read_length=s" => \$read_length,
            "date=s" => \$date,
            "submitter=s" => \$submitter);


if ((!$project_name) || (!$flowcell_name) || (!$flowcell_path) || (!$seq_center) || (!$submitter)) {
	die "usage: $0 --project_name PSP --flowcell_name Project_50260 --flowcell_path /path/to/Project_50260 --seq_center PGFI --read_length 2x100 --date 2011-06-10 --submitter Geller [--debug]\n(use --debug to preview what would be inserted into mysql table)\n";
}

my $table = `basename $0 .pl | sed s/insert//`;
chomp($table);
printf STDERR "Inserting $flowcell_name into table $table\n";
if ($debug) {
	printf "Debug mode. The following are aguments\n";
	print Dumper(@argv);
}
else {
	my $newid=driver();
	printf STDERR "${project_name}_${flowcell_name} %s\n", ($newid) ? "inserted into $table with FID=$newid" : "already in $table\n\n";
}

sub driver {
	my $dbh = DBI->connect($ENV{dbi1}, $ENV{dbi2}, $ENV{dbi3}) or die "Couldn't connect to database: " . DBI->errstr;;
	my $pi = MyTools::fetchrow1col1_arrayref($dbh, "select Owner from Project where ", {'ProjectName' => $project_name}) or die "Project $project_name not found\n";
	my $record_present = MyTools::fetchrow1col1_arrayref($dbh, "select FID from Flowcell where ", {'FlowcellName' => $flowcell_name});
	if (defined($record_present)) {
		printf STDERR "Existing FID=%d ", $record_present;
		return 0;
	}
	my $sth = $dbh->prepare("INSERT INTO $table (PI,FlowcellName,ReadLength,SeqCenter,SeqCenterReqDate,PathDir,Submitter) VALUES (?,?,?,?,?,?,?)") or die "Couldn't prepare statement: " . $dbh->errstr;
	$sth->execute($pi, $flowcell_name, $read_length, $seq_center, $date, $flowcell_path, $submitter) or die "Couldn't execute statement: " . $sth->errstr;
	return MyTools::fetchrow1col1_arrayref($dbh, "select FID from $table where ", {'FlowcellName' => $flowcell_name});
}
